﻿#include <QMessageBox>
#include <QByteArray>
#include <QMetaEnum>
#include <QFile>
#include <String>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "comfunc_qt.h"
#include "updata_protocol.h"
#include "collector_protocol.h"
#include "parse_clct_frame.h"


#define SCAN_ICON QApplication::style()->standardIcon((enum QStyle::StandardPixmap)59)

serial_ui *serial;

MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serial = new serial_ui( ui->ComboName,
                            ui->ComboBaudRate,
                            ui->ComboDataBits,
                            ui->ComboStopBits,
                            ui->ComboParity,
                            ui->ComboFlowControl,
                            ui->btn_toggleCom);
    serial->init_ui_set_split_frame_time(ui->spinBox_splitFrame);
    ui->pushButton_scanCom->setIcon(SCAN_ICON);
    QObject::connect(serial,SIGNAL(received_data()),this,SLOT(on_rcv_serial_data()));
    QObject::connect(serial,SIGNAL(put_visual_infor(QString)),
                     this,SLOT(on_serial_op_output_infor(QString)));//串口发出可视化的操作提示信息
    QObject::connect(serial,SIGNAL(show_send_data(QString, QString, QString, QString)),
                     this,SLOT(on_rcv_for_tableWidget(QString, QString, QString, QString)));//串口发出数据后，发信号
    serial->set_split_frame_time(100);
    serial->scan();
    init_update();
}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::on_pushButton_scanCom_clicked()
{
    serial->scan();
}

void MainWindow::on_pushButton_send_clicked()
{
    uint8_t buf[500];
    int len;

    QString ui_frame_str = ui->textEdit_input->toPlainText();
    QString err_info = "转换成功";
    len = hex_str_to_byte_arr(ui_frame_str, buf, sizeof(buf), true, err_info);
    qDebug()<<err_info;
    if(len < 0)
    {
        ui->textEdit_show->append(err_info.toUtf8());
        return;
    }

    serial->send_data(buf, len);
}
void MainWindow::on_rcv_serial_data(void)
{
    uint8_t buf[500];
    uint16_t len;
    len = serial->read((char*)buf, sizeof(buf));
    qDebug()<<"app rcv len=" << len;

    ui->tableWidget_show->append_hex_string_to_last_row("接收", buf, len);

    struct clct_frame *pFrame = (struct clct_frame *)get_collector_frame(buf, len);
    if(NULL != pFrame)
    {
        uint16_t ret_len = handle_clct_frame(pFrame);
        serial->send_data((uint8_t*)pFrame, ret_len);
    }
    else
    {
        qDebug()<<"报文格式不是57";
    }
}

void MainWindow::on_serial_op_output_infor(QString infor)
{
    ui->textEdit_show->moveCursor(QTextCursor::End);
    ui->textEdit_show->append(infor);
}

void MainWindow::on_pushButton_loadFile_clicked()
{
    QString filePath = ui->textEdit_filePath->toPlainText();//file:///E:/test/a.bin
    filePath.replace("file:///","");


    pFile->setFileName(filePath);

    if (!pFile->open(QIODevice::ReadOnly))//追加模式QIODevice::Append
    {
        ui->textEdit_show->append(("读文件->失败，文件路径:") + filePath );
        return;
    }
    else
    {
        ui->textEdit_show->append("读文件->success");
        ui->textEdit_show->append(QString("size = %1 B ≈ %2*1024 B").arg(pFile->size()).arg(pFile->size()/1024.0));
        ui->textEdit_show->append(QString("%1 / 448 = %2").arg(pFile->size()).arg(pFile->size()/448.0));
        if(pFile->size() > 300 * 1024)
            QMessageBox::warning(this,("错误"),("文件不得超过300K！"));

    }
}


void MainWindow::on_pushButton_simulateHandle_clicked()
{
    uint8_t buf[500];
    int len;

    //QString ui_frame_str = ui->textEdit_simulateRcv->toPlainText();
    QString ui_frame_str = ui->comboBox_simulateFrame->currentText();
    qDebug()<<"模拟的报文："<<ui_frame_str;
    len = hex_str_to_byte_arr(ui_frame_str, buf, sizeof(buf), true);
    if(len < 0)
    {
        qDebug()<<"QString转数组失败：err num"<< len;
        return;
    }
    else
    {
        qDebug()<<"QString转数组ok,len = "<< len;
    }


    struct clct_frame *pFrame = (struct clct_frame *)get_collector_frame(buf, len);
    if(NULL != pFrame)
    {
        uint16_t ret_len = handle_clct_frame(pFrame);
        serial->send_data((uint8_t*)pFrame, ret_len);
    }
    else
    {
        qDebug()<<("报文格式不是57");
    }
}

void MainWindow::on_tableWidget_show_clicked(const QModelIndex &index)
{
    int Row = index.row();
    QString frame_str = ui->tableWidget_show->item(Row,3)->text();
    //qDebug()<<("选中了第%d行").arg(Row);
    //qDebug()<<("报文内容是:")<<frame_str;
    QString parse_str;
    uint8_t dir;
    if(ui->radioButton_down->isChecked())
        dir = DOWN_STREAM;
    else
        dir = UP_STREAM;
    frame_parse(frame_str, parse_str, dir);
    ui->textEdit_parse->setText(parse_str);

}

void MainWindow::on_rcv_for_tableWidget(QString dir_str, QString byte_cnt_str, QString frame_str, QString frame_char_str)
{
    ui->tableWidget_show->append_hex_string_to_last_row(dir_str, byte_cnt_str, frame_str, frame_char_str);
}



void MainWindow::on_pushButton_continueUpdate_clicked()
{
    update_continue();
}

void MainWindow::on_pushButton_losePkt_clicked()
{
    update_lose_pkt();
}

void MainWindow::on_pushButton_pauseUpdate_clicked()
{
    update_stop();
}
void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    ui->textEdit_input->setPlainText(arg1);
}
